import { observable, action } from "mobx-miniprogram";
import { logout, updateInfo } from "@/api/index";
import { cache } from "@/util/index";
export const userStore = observable({
  userInfo: {},
  roles: [],
  islogin: false,
  initUserInfo: action(function (this: any) {
    const user = cache.get("user") || "{}";
    const exp = cache.get("token_expired");
    if (Date.now() < exp) {
      let userInfo = JSON.parse(user);
      this.userInfo = userInfo;
      this.roles = userInfo.role;
      this.islogin = true;
    }
  }),
  updateInfo: action(async function (this: any, data: Object) {
    try {
      await updateInfo(data);
      this.userInfo = Object.assign(this.userInfo, data);
    } catch {
      return false;
    }
  }),
  changePineCoin: action(function (this: any, coin: number) {
    let currentCoin: number = this.userInfo.pine_cone_balance;
    let newCoin: number = 0;
    if (coin > 0) newCoin = currentCoin + coin;
    if (coin < 0) newCoin = currentCoin - coin;
    this.userInfo.pine_cone_balance = newCoin;
    cache.set("user", JSON.stringify(this.userInfo));
  }),
  setUserInfo: action(function (this: any, userInfo: Object) {
    this.userInfo = userInfo;
    this.roles = userInfo.role;
    this.islogin = true;
    cache.set("user", JSON.stringify(userInfo));
  }),
  logout: action(async function (this: any) {
    await logout();
    this.userInfo = {};
    this.roles = [];
    this.islogin = false;
    cache.remove(["user", "token", "uid", "token_expired"]);
  }),
});
